package ch.prokopovi.provider.places;

import java.util.List;
import java.util.Map.Entry;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import android.test.AndroidTestCase;
import android.util.Log;
import ch.prokopovi.api.provider.PlacesProvider;
import ch.prokopovi.api.struct.BestRatesRecord;
import ch.prokopovi.err.WebUpdatingException;
import ch.prokopovi.provider.ProviderUtils;
import ch.prokopovi.struct.Master.Region;

public class MyfinProviderTest extends AndroidTestCase {

    private static final String LOG_TAG = "MyfinProviderTest";

    private PlacesProvider provider;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        this.provider = new MyfinPlacesProvider();
    }


    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testUpdate() throws WebUpdatingException {

        List<Entry<Long, BestRatesRecord>> places = this.provider.getPlaces(Region.BREST);

        for (Entry<Long, BestRatesRecord> entry : places) {

            Log.d(LOG_TAG, "place " + entry.getKey()+ " : "+entry.getValue());
        }

        assertNotNull("result is null", places);
        assertTrue("result is empty", places.size() > 0);
    }

    public void testParsing() throws WebUpdatingException, XPatherException {


        HtmlCleaner cleaner = ProviderUtils.initHtmlCleaner();

        String testStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
                "<root>"+
                "<bank1142>"+
                "<date>16.03.2013</date>"+
                "<bankname>bank name</bankname>"+
                "<bankaddress>bank adress</bankaddress>"+
                "<bankphone></bankphone>"+
                "<usd_buy>-</usd_buy>"+
                "<usd_sell>-</usd_sell>"+
                "<eur_buy>-</eur_buy>"+
                "<eur_sell>-</eur_sell>"+
                "<rur_buy>-</rur_buy>"+
                "<rur_sell>282</rur_sell>"+
                "<eurusd_buy>-</eurusd_buy>"+
                "<eurusd_sell>-</eurusd_sell>"+
                "</bank1142>"+
                "</root>";


        TagNode node = cleaner.clean(testStr);

        Object[] nodes = node.evaluateXPath("//root/*");

        if (nodes != null) {

            for (Object obj : nodes) {
                TagNode tmp = (TagNode) obj;

                // Log.d(LOG_TAG, "string " + tmp.getText());

                List<Entry<Long, BestRatesRecord>> entries = MyfinPlacesProvider.parsePlace(tmp);

                for (Entry<Long, BestRatesRecord> entry : entries) {
                    assertNotNull("rate should not be null. rate: "+entry, entry.getValue());
                }

            }
        }

    }
}
